package com.qianfeng.smartdevice.websocket.handler;

import com.qianfeng.smartdevice.event.ColorCommandEvent;
import com.qianfeng.smartdevice.execption.MyErrorCode;
import com.qianfeng.smartdevice.execption.QueryDataErrorException;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

/**
 * Created by wenka on 2022/3/27 20:06
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
@Component
public class ColorCommandHandler extends BaseCommandHandler {
    @EventListener
    public void onEvent(ColorCommandEvent event) {
        System.out.println("颜色控制器发送命令");
        String deviceId = event.getDeviceId();
        String command = event.getCommand();
        //获取到会话
        WebSocketSession webSocketSession = getAllClients().get(deviceId);
        Assert.isTrue(webSocketSession != null && webSocketSession.isOpen(), () -> {
            throw new QueryDataErrorException("设备不在线", MyErrorCode.DEVICE_OFFLINE);
        });
        try {
            webSocketSession.sendMessage(new TextMessage(command));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
